import { netUrl, reqTimeout, showNetRequest } from '../../config';
import tools from './index';
import { Modal, notification } from 'antd';
import router from 'umi/router';

// 此乃网络请求后台接口之凭证!
let token = '', userId = 0;

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

const checkStatus = response => {
  if (response.status >= 400) {
    const errortext = codeMessage[response.status] || response.statusText;
    notification.error({
      message: `请求错误 ${response.status}: ${response.url}`,
      description: errortext,
    });
    if (response.status === 403) {
      router.push('/exception/403');
    } else if (response.status >= 404 && response.status < 422) {
      router.push('/exception/404');
    } else if (response.status <= 504 && response.status >= 500) {
      router.push('/exception/500');
    }
  }
  return response;
};

function requestPlus(path, para, second = reqTimeout, reqType = 'json', any = false) {
  const url = any ? path : netUrl() + path;
  const isLogin = path.indexOf('login') >= 0;
  if (!isLogin && (!token || !userId)) {
    const tk = tools.funcGetToken();
    const uid = tools.funcGetUserId();
    if (tk && uid) {
      token = tk;
      userId = uid;
      return requestFunc();
    } else {
      document.location.pathname = '/user/login';
    }
  } else return requestFunc();

  function requestFunc() {
    if (!isLogin) {
      // 自动附上访问令牌
      para.token = token;
      para.userId = userId;
    }
    if (showNetRequest) {
      console.log('================================================================');
      console.log('request url', url);
      console.log('request params', para);
    }
    const params = {
      method: 'POST',
      headers: { Accept: 'application/json' },
    };
    if (reqType === 'json') {
      // json请求
      params.headers['Content-Type'] = 'application/json; charset=utf-8';
      params.body = JSON.stringify(para);
    } else if (reqType === 'form') {
      // form请求
      params.headers['Content-Type'] = 'application/x-www-form-urlencoded';
      params.body = para;
      // params.headers.mode = 'no-cors';
    }

    return Promise.race([
      fetch(url, params),
      new Promise((resolve, reject) => {
        setTimeout(() => reject(new Error('网络请求超时')), second * 1000);
      }),
    ])
      .then(checkStatus)
      .then(response => {
        return response.json();
      })
      .then(response2 => {
        if (showNetRequest) {
          console.log('response', response2);
        }
        if (response2) {
          if (!response2.success && response2.status === 401) {
            // 状态码"401"来源于: /src/common/web/controller/TokenCheckRequest:
            // return nil, &JsonMsg{false, "登录状态已失效，请重新登录！", 401}
            Modal.confirm({
              title: '登录状态异常',
              content: response2.msg,
              okText: '好',
              cancelText: '不',
              onOk: () => {
                document.location.hash = '#/user/login';
                window.parent.document.location.reload();
                // document.location.pathname = '/user/login';
              },
            });
          }
        } else {
          notification.error({ message: url, description: '接口返回为null' });
        }
        return response2;
      })
      .catch(err => {
        let description = err.toString();
        if (description.indexOf('Failed to fetch') >= 0) description = '网络连接失败';
        notification.error({ message: url, description });
        return {
          msg: description,
          success: false,
          status: -1,
        };
      });
  }
}

export default requestPlus;
